import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/chart_configs.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

String cellText = 'siteMonitor.cell'.tr; //电芯
String tempText = 'siteMonitor.temperature'.tr; // 温度;
String voltageText = 'siteMonitor.voltage'.tr; //电压

class BmuBarChart extends StatefulWidget {
  final int? deviceId;
  final int? productId;
  const BmuBarChart(this.deviceId, this.productId, {super.key});

  @override
  State<BmuBarChart> createState() => _BmuBarChartState();
}

class _BmuBarChartState extends State<BmuBarChart> {
  UseSubsribe subsribe = UseSubsribe();

  StreamController<Map<String, dynamic>>? streamController;

  StreamSubscription? _subscription;

  List<String> allLabels = [];

  List sourceDataset = [];

  final liquidEnergyBatteryProductIds = [
    ProductIDType.newLiquidCoolingEnergyBattery.value,
    ProductIDType.liquidEnergyBatteryStack.value,
    ProductIDType.liquidEnergy232BatteryPack.value,
  ];

  Map<int, List<String>> labelMap = {
    ProductIDType.liquidEnergy232.value: [
      '${tempText}1',
      '${cellText}1',
      '${tempText}2',
      '${cellText}2',
      '${cellText}3',
      '${tempText}3',
      '${cellText}4',
      '${cellText}5',
      '${tempText}4',
      '${cellText}6',
      '${cellText}7',
      '${tempText}5',
      '${cellText}8',
      '${cellText}9',
      '${tempText}6',
      '${cellText}10',
      '${cellText}11',
      '${tempText}7',
      '${cellText}12',
      '${cellText}13',
      '${tempText}8',
      '${cellText}14',
      '${cellText}15',
      '${cellText}16',
      '${tempText}9',
      '${cellText}17',
      '${cellText}18',
      '${tempText}10',
      '${cellText}19',
      '${cellText}20',
      '${tempText}11',
      '${cellText}21',
      '${cellText}22',
      '${tempText}12',
      '${cellText}23',
      '${cellText}24',
      '${tempText}13',
      '${cellText}25',
      '${cellText}26',
      '${tempText}14',
      '${cellText}27',
      '${tempText}15',
      '${tempText}16',
      '${cellText}28',
      '${cellText}29',
      '${tempText}17',
      '${cellText}30',
      '${cellText}31',
      '${tempText}18',
      '${cellText}32',
      '${cellText}33',
      '${tempText}19',
      '${cellText}34',
      '${cellText}35',
      '${tempText}20',
      '${cellText}36',
      '${cellText}37',
      '${tempText}21',
      '${cellText}38',
      '${cellText}39',
      '${tempText}22',
      '${cellText}40',
      '${cellText}41',
      '${cellText}42',
      '${tempText}23',
      '${cellText}43',
      '${cellText}44',
      '${tempText}24',
      '${cellText}45',
      '${cellText}46',
      '${tempText}25',
      '${cellText}47',
      '${cellText}48',
      '${tempText}26',
      '${cellText}49',
      '${cellText}50',
      '${tempText}27',
      '${cellText}51',
      '${cellText}52',
      '${tempText}28',
      '${tempText}29',
    ],
  };

  bool get isLiquidEnergyBatteryPack =>
      liquidEnergyBatteryProductIds.contains(widget.productId);

  @override
  void initState() {
    allLabels = getLables();

    super.initState();

    if (widget.deviceId != null) {
      streamController = subsribe.start([widget.deviceId!], true);
    }
  }

  @override
  void didUpdateWidget(covariant BmuBarChart oldWidget) {
    if (oldWidget.deviceId != widget.deviceId) {
      if (oldWidget.deviceId != null) {
        subsribe.start([oldWidget.deviceId!], false);
      }

      if (widget.deviceId != null) {
        streamController = subsribe.start([widget.deviceId!], true);
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void dispose() {
    // subsribe.start([widget.deviceId], false);
    subsribe.closeListen();
    _subscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 250.h,
      color: Colour.white,
      child: StreamBuilder(
        stream: streamController?.stream,
        builder: (context, snapshot) =>
            Echarts(captureVerticalGestures: false, option: '''
          {
            grid: {
              bottom: 70,
            },
            legend:{
              show:true,
              icon:'rect',
              itemWidth:12,
              itemHeight:3,
              right:16,
              itemStyle:{
                borderCap:'round'
              },
              left: 'center',
              top: '8%',
            },
            tooltip: {
              show: true,
              trigger: 'axis',
              formatter: (params) => {
                const { value, name } = (params || {})[0];
                return name + '：' + (value[1] === '' ? value[2] + '℃' : value[1] + 'V');
              },
            },
            xAxis: {
              type: 'category',
              axisLine: {
                show: true,
              },
              axisLabel: {
                showMaxLabel: true,
              },
              axisTick: {
                alignWithLabel: true,
                show: true,
              },
            },
            yAxis: [
              {
                name: '${ResKey.gunVoltage.tr}',
                type: 'value',
                axisLine: {
                  show: false,
                },
                axisTick: {
                  show: false,
                },
                  max: ${getMax(snapshot.data, max: 10)} ?? undefined ,
                  min: ${getMin(snapshot.data, min: 0)} ?? undefined ,
              },
              {
                name: '${ResKey.temperature.tr}',
                type: 'value',
                axisLine: {
                  show: false,
                },
                axisTick: {
                  show: false,
                },
              },
            ],
            dataset: {
                source: ${getChartOption(snapshot.data)},
            },
            series: [
              {
                type: 'bar',
                barMaxWidth: 10,
                stack: 'Total',
                yAxisIndex: 0,
                itemStyle: {
                  color: 'rgba(0, 125, 255, 1)',
                  borderRadius: [4, 4, 0, 0] 
                },
              },
              {
                type: 'bar',
                barMaxWidth: 10,
                yAxisIndex: 1,
                stack: 'Total',
                itemStyle: {
                  color: 'rgba(61, 213, 152, 1)',
                  borderRadius: [4, 4, 0, 0] 
                },
              },
            ],
          }

         '''),
      ),
    );
  }

  List<String> getLables() {
    List<String> result = [];
    result = labelMap[widget.productId] ?? [];
    if (result.isNotEmpty) {
      return result;
    }

    var tempNum = 2;
    List.generate(
        isLiquidEnergyBatteryPack
            ? ProductIDType.liquidEnergy232BatteryPack.value == widget.productId
                ? 52
                : 48
            : 24, (index) {
      var num = index + 1;
      result.add('$cellText$num');
      if (isLiquidEnergyBatteryPack) {
        if (num % 2 == 1) {
          result.add(
            '$tempText$tempNum', //温度
          );
          tempNum++;
        }
        if (num % 12 == 0) {
          result.add(
            '$tempText$tempNum', //温度
          );
          tempNum++;
        }
      } else {
        if (num % 2 == 0) {
          result.add('$tempText${num ~/ 2}');
        }
      }
    });
    if (isLiquidEnergyBatteryPack) {
      result.insert(0, '${tempText}1' //温度

          );
    } else {
      result.add('${tempText}13'); //温度13
    }

    return result;
  }

  getChartOption(Map<String, dynamic>? dataSource) {
    var source = [
      ['product', voltageText, tempText],
    ];

    for (var item in allLabels) {
      var num = item.replaceFirst(cellText, '').replaceFirst(tempText, '');
      var value, resultValue;
      if (item.contains(cellText)) {
        value = dataSource?['Voltage$num'] ?? '';
      } else {
        value = dataSource?['Temperature$num'] ?? '';
      }
      resultValue = value;
      if (resultValue != null) {
        resultValue = resultValue.toString();
      }

      source.add([
        item,
        ...(item.contains(cellText) ? [resultValue, ''] : ['', resultValue])
      ]);
    }

    return source.map((e) => jsonEncode(e)).toList();
  }

  double? getMax(Map<String, dynamic>? dataSource, {required double max}) {
    if (dataSource == null) {
      return max;
    }
    num maxValue = 0;
    for (var item in allLabels) {
      var num = item.replaceFirst(cellText, '').replaceFirst(tempText, '');
      var value;
      if (item.contains(cellText)) {
        value = dataSource['Voltage$num'] ?? 0;
      } else {
        value = dataSource['Temperature$num'] ?? 0;
      }
      if (value > maxValue) {
        maxValue = value;
      }
    }
    if (maxValue > max) {
      return null;
    } else {
      return max;
    }
  }

  double? getMin(Map<String, dynamic>? dataSource, {required double min}) {
    if (dataSource == null) {
      return min;
    }
    double minValue = 0;
    for (var item in allLabels) {
      var num = item.replaceFirst(cellText, '').replaceFirst(tempText, '');
      var value;
      if (item.contains(cellText)) {
        value = dataSource['Voltage$num'] ?? 0;
      } else {
        value = dataSource['Temperature$num'] ?? 0;
      }
      if (value < minValue) {
        minValue = value;
      }
    }
    if (minValue < min) {
      return null;
    } else {
      return min;
    }
  }
}
